<template>
  <view>
    <!-- 搜索框 -->
    <view class="search-box">
      <uni-search-bar @input="input" :radius="100" cancel-button="none"></uni-search-bar>
    </view>

    <!-- 搜索结果 -->
    <view class="sugg-list" v-if="searchResults.length !== 0">
      <view class="sugg-item" v-for="(item,i) in searchResults" :key="i" @click="gotoDetail(item)">
        <view class="goods-name">
          {{item.goods_name}}
        </view>
        <uni-icons type="right" size="17"></uni-icons>
      </view>
    </view>

    <!-- 搜索历史 -->
    <view class="history-box" v-else>
      <!-- 搜索历史标题 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="clean"></uni-icons>
      </view>
      <!-- 搜索历史内容 -->
      <view class="history-list">
        <view class="history-item" v-for="(item,i) in histories" :key="i" @click="gotoGoodsList(item)">{{item}} </view>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer: null,
        //搜索关键词
        keyWrods: '',
        searchResults: [],
        historyList: []
      };
    },
    computed: {
      histories() {
        //由于histroy数组都是在最后添加，最新的搜索词要在最前展示，所以进行反转
        //由于数组是引用类型，所以不要直接基于原数组调用reverse方法，以免修改原数组中的数据
        //而是应该新建一个内存无关的数组，再进行rever反转
        return [...this.historyList].reverse()
      }
    },
    onLoad() {

      this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
    },

    methods: {
      input(e) {

        //连续输入时，清楚上次的延时器
        clearTimeout(this.timer)

        // 防抖动,通过延时500ms防止每次输入都输出
        this.timer = setTimeout(() => {
          this.keyWrods = e
          console.log(this.keyWrods)
          this.getSearchList()
        }, 500)

      },
      async getSearchList() {
        if (this.keyWrods.length === 0) {
          this.searchResults = []
          return
        }

        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/qsearch', {
          'query': this.keyWrods
        })
        if (res.meta.status !== 200) return uni.$showMsg()
        this.searchResults = res.message
        //将关键词存入历史
        this.saveSearchHistroy();
      },
      gotoDetail(item) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      },
      saveSearchHistroy() {

        //利用Set对象新增重复值时，不会添加的特性，去除重复项

        //1.将Array数组转化为Set对象
        const set = new Set(this.historyList);
        //2.调用Set对象的delete方法，移除对应的元素，这样将相同的元素添加在最后
        set.delete(this.keyWrods)
        //3.将this.keyWrods添加到集合最后,这样反转后，将在第一个显示
        set.add(this.keyWrods)
        //4.将Set对象转化为Array数组
        this.historyList = Array.from(set)

        //5.保存在本地，持久化
        uni.setStorageSync('kw', JSON.stringify(this.historyList))

      },

      clean() {
        this.historyList = []
        uni.setStorageSync('kw', '[]')
      },
      gotoGoodsList(kw) {
        uni.navigateTo({
          url: '/subpkg/goods_list/goods_list?query=' + kw
        })
      }
    },


  }
</script>

<style lang="scss">
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;

  }

  .sugg-list {
    padding: 0 5px;

    .sugg-item {
      display: flex;
      align-items: center;
      justify-content: space-between;

      padding: 13px 0;
      border-bottom: 1px solid #efefef;
      font-size: 12px;

      .goods-name {
        //文字不允许换行
        white-space: nowrap;
        //溢出部分隐藏
        overflow: hidden;
        //文本溢出后，使用...代替
        text-overflow: ellipsis;


      }

    }
  }

  .history-box {
    padding: 0 5px;

    .history-title {
      display: flex;
      justify-content: space-between;
      height: 40px;
      align-items: center;
      font-size: 13px;
      border-bottom: 1px solid #efefef;
    }

    .history-list {
      display: flex;
      flex-wrap: wrap;

      .history-item {
        margin-top: 5px;
        margin-right: 5px;
        padding: 5px 10px;
        align-items: center;
        border-radius: 5px;
        background-color: #FFFFFF;

        font-size: 13px;
      }

    }
  }
</style>